<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="C++知识点汇总, 天机阁">
    <meta name="description" content="

数据类型
typedef
类型限定符
定义常量
存储类
引用 vs 指针
struct vs class
成员函数
析构函数
拷贝构造函数
friend 友元
inline 内联函数
继承类型
运算符重载
动态内存
命名空间
预处理器
">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>C++知识点汇总 | 天机阁</title>
    <link rel="icon" type="image/png" href="/hello-world/favicon.png">
    


    <!-- bg-cover style     -->



<link rel="stylesheet" type="text/css" href="/hello-world/libs/awesome/css/all.min.css">
<link rel="stylesheet" type="text/css" href="/hello-world/libs/materialize/materialize.min.css">
<link rel="stylesheet" type="text/css" href="/hello-world/libs/aos/aos.css">
<link rel="stylesheet" type="text/css" href="/hello-world/libs/animate/animate.min.css">
<link rel="stylesheet" type="text/css" href="/hello-world/libs/lightGallery/css/lightgallery.min.css">
<link rel="stylesheet" type="text/css" href="/hello-world/css/matery.css">
<link rel="stylesheet" type="text/css" href="/hello-world/css/my.css">
<link rel="stylesheet" type="text/css" href="/hello-world/css/dark.css" media="none" onload="if(media!='all')media='all'">




    <link rel="stylesheet" href="/hello-world/libs/tocbot/tocbot.css">
    <link rel="stylesheet" href="/hello-world/css/post.css">




    
        <link rel="stylesheet" type="text/css" href="/hello-world/css/reward.css">
    



    <script src="/hello-world/libs/jquery/jquery-3.6.0.min.js"></script>

<meta name="generator" content="Hexo 6.3.0"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/hello-world/" class="waves-effect waves-light">
                    
                    <img src="/hello-world/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">天机阁</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/hello-world/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
  <li>
    <a href="javascript:;" class="waves-effect waves-light" onclick="switchNightMode()" title="深色/浅色模式" >
      <i id="sum-moon-icon" class="fas fa-sun" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/hello-world/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">天机阁</div>
        <div class="logo-desc">
            
            或许不知是梦的缘故，流离之人总在追逐幻影
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/hello-world/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/hello-world/medias/featureimages/1.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">C++知识点汇总</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/hello-world/tags/%E5%AD%A6%E4%B9%A0/">
                                <span class="chip bg-color">学习</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2022-11-28
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <ul>
<li><a href="#"></a></li>
<li><a href="#%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B">数据类型</a></li>
<li><a href="#typedef">typedef</a></li>
<li><a href="#%E7%B1%BB%E5%9E%8B%E9%99%90%E5%AE%9A%E7%AC%A6">类型限定符</a></li>
<li><a href="#%E5%AE%9A%E4%B9%89%E5%B8%B8%E9%87%8F">定义常量</a></li>
<li><a href="#%E5%AD%98%E5%82%A8%E7%B1%BB">存储类</a></li>
<li><a href="#%E5%BC%95%E7%94%A8-vs-%E6%8C%87%E9%92%88">引用 vs 指针</a></li>
<li><a href="#struct-vs-class">struct vs class</a></li>
<li><a href="#%E6%88%90%E5%91%98%E5%87%BD%E6%95%B0">成员函数</a></li>
<li><a href="#%E6%9E%90%E6%9E%84%E5%87%BD%E6%95%B0">析构函数</a></li>
<li><a href="#%E6%8B%B7%E8%B4%9D%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0">拷贝构造函数</a></li>
<li><a href="#friend-%E5%8F%8B%E5%85%83">friend 友元</a></li>
<li><a href="#inline-%E5%86%85%E8%81%94%E5%87%BD%E6%95%B0">inline 内联函数</a></li>
<li><a href="#%E7%BB%A7%E6%89%BF%E7%B1%BB%E5%9E%8B">继承类型</a></li>
<li><a href="#%E8%BF%90%E7%AE%97%E7%AC%A6%E9%87%8D%E8%BD%BD">运算符重载</a></li>
<li><a href="#%E5%8A%A8%E6%80%81%E5%86%85%E5%AD%98">动态内存</a></li>
<li><a href="#%E5%91%BD%E5%90%8D%E7%A9%BA%E9%97%B4">命名空间</a></li>
<li><a href="#%E9%A2%84%E5%A4%84%E7%90%86%E5%99%A8">预处理器</a><ul>
<li><a href="#include">#include</a></li>
<li><a href="#define">#define</a></li>
<li><a href="#%E6%9D%A1%E4%BB%B6%E7%BC%96%E8%AF%91">条件编译</a></li>
<li><a href="#%E9%A2%84%E5%AE%9A%E4%B9%89%E5%AE%8F">预定义宏</a></li>
</ul>
</li>
<li><a href="#%E4%BF%A1%E5%8F%B7">信号</a></li>
<li><a href="#%E7%BA%BF%E7%A8%8B">线程</a></li>
<li><a href="#%E5%BC%BA%E5%88%B6%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2">强制类型转换</a><ul>
<li><a href="#const_cast">const_cast</a></li>
<li><a href="#static_cast">static_cast</a></li>
<li><a href="#dynamic_cast">dynamic_cast</a></li>
<li><a href="#reinterupt_cast">reinterupt_cast</a></li>
</ul>
</li>
<li><a href="#%E6%99%BA%E8%83%BD%E6%8C%87%E9%92%88">智能指针</a><ul>
<li><a href="#unique_ptr">unique_ptr</a></li>
<li><a href="#shared_ptr">shared_ptr</a></li>
<li><a href="#weak_ptr">weak_ptr</a></li>
</ul>
</li>
<li><a href="#%E5%86%85%E5%AD%98%E7%A9%BA%E9%97%B4">内存空间</a></li>
</ul>
<h2 id="头文件"><a href="#头文件" class="headerlink" title="头文件"></a>头文件</h2><p><strong>.h</strong> 文件中能包含：</p>
<ul>
<li>类成员数据的声明，但不能赋值</li>
<li>类静态数据成员的定义和赋值，但不建议</li>
<li>类的成员函数的声明</li>
<li>非类成员函数的声明</li>
<li>常数的定义：如：constint a&#x3D;5;</li>
<li>静态函数的定义</li>
<li>类的内联函数的定义</li>
</ul>
<p>不能包含：</p>
<ul>
<li>所有非静态变量（不是类的数据成员）的声明</li>
<li>默认命名空间声明不要放在头文件，using namespace std; 等应放在 .cpp 中，在 .h 文件中使用 std::string</li>
</ul>
<h2 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h2><p>|类型	|位<br>|–|–|–<br>|char	|1 个字节	<br>|int	|4 个字节	<br>|short int	|2 个字节	<br>|long int	|8 个字节	<br>|float	|4 个字节	<br>|double	|8 个字节	<br>|long double	|16 个字节	<br>|wchar_t	|2 或 4 个字节	</p>
<h2 id="typedef"><a href="#typedef" class="headerlink" title="typedef"></a>typedef</h2><p>使用 typedef 为一个已有的类型取一个新的名字</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> type newname; </span><br></pre></td></tr></table></figure>

<h2 id="类型限定符"><a href="#类型限定符" class="headerlink" title="类型限定符"></a>类型限定符</h2><table>
<thead>
<tr>
<th>限定符</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>const</td>
<td>const 类型的对象在程序执行期间不能被修改改变。</td>
</tr>
<tr>
<td>volatile</td>
<td>修饰符 volatile 告诉编译器不需要优化volatile声明的变量，让程序可以直接从内存中读取变量。对于一般的变量编译器会对变量进行优化，将内存中的变量值放在寄存器中以加快读写效率。</td>
</tr>
<tr>
<td>restrict</td>
<td>由 restrict 修饰的指针是唯一一种访问它所指向的对象的方式。只有 C99 增加了新的类型限定符 restrict。</td>
</tr>
</tbody></table>
<h2 id="定义常量"><a href="#定义常量" class="headerlink" title="定义常量"></a>定义常量</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用 #define 预处理器</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> LENGTH 10</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// const 关键字</span></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> WIDTH  = <span class="number">5</span>;</span><br></pre></td></tr></table></figure>

<h2 id="存储类"><a href="#存储类" class="headerlink" title="存储类"></a>存储类</h2><table>
<thead>
<tr>
<th>存储类</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>auto</td>
<td>声明变量时根据初始化表达式自动推断该变量的类型</td>
</tr>
<tr>
<td>register</td>
<td>用于定义存储在寄存器中而不是 RAM 中的局部变量，用于需要快速访问的变量，不能对它应用一元的 ‘&amp;’ 运算符（因为它没有内存位置）</td>
</tr>
<tr>
<td>static</td>
<td>用在类数据成员上时，会导致仅有一个该成员的副本被类的所有对象共享；修饰全局变量时，会使变量的作用域限制在声明它的文件内</td>
</tr>
<tr>
<td>extern</td>
<td>全局变量的引用，全局变量对所有的程序文件都是可见</td>
</tr>
<tr>
<td>mutable</td>
<td></td>
</tr>
<tr>
<td>thread_local</td>
<td>仅可在它在其上创建的线程上访问，变量在创建线程时创建，并在销毁线程时销毁，每个线程都有其自己的变量副本</td>
</tr>
</tbody></table>
<h2 id="引用-vs-指针"><a href="#引用-vs-指针" class="headerlink" title="引用 vs 指针"></a>引用 vs 指针</h2><ul>
<li>不存在空引用。引用必须连接到一块合法的内存。</li>
<li>一旦引用被初始化为一个对象，就不能被指向到另一个对象。指针可以在任何时候指向到另一个对象。</li>
<li>引用必须在创建时被初始化。指针可以在任何时间被初始化。</li>
</ul>
<h2 id="struct-vs-class"><a href="#struct-vs-class" class="headerlink" title="struct vs class"></a>struct vs class</h2><p>class 和 struct 定义类的唯一区别是默认的反问权限，struct 默认是 public，class 默认是 private。</p>
<h2 id="成员函数"><a href="#成员函数" class="headerlink" title="成员函数"></a>成员函数</h2><p>成员函数可以在类的外部使用范围解析运算符 :: 定义该函数</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">double</span> <span class="title">Box::getVolume</span><span class="params">(<span class="type">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> length * breadth * height;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="析构函数"><a href="#析构函数" class="headerlink" title="析构函数"></a>析构函数</h2><p>析构函数是类的一种特殊的成员函数，它会在每次删除所创建的对象时执行</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Line</span></span><br><span class="line">&#123;</span><br><span class="line">   <span class="keyword">public</span>:</span><br><span class="line">      ~<span class="built_in">Line</span>();  <span class="comment">// 这是析构函数声明</span></span><br><span class="line"> </span><br><span class="line">   <span class="keyword">private</span>:</span><br><span class="line">      <span class="type">double</span> length;</span><br><span class="line">&#125;;</span><br><span class="line"> </span><br><span class="line">Line::~<span class="built_in">Line</span>(<span class="type">void</span>)</span><br><span class="line">&#123;</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;Object is being deleted&quot;</span> &lt;&lt; endl;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="拷贝构造函数"><a href="#拷贝构造函数" class="headerlink" title="拷贝构造函数"></a>拷贝构造函数</h2><p>拷贝构造函数是一种特殊的构造函数，它在创建对象时，是使用同一类中之前创建的对象来初始化新创建的对象。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Line</span></span><br><span class="line">&#123;</span><br><span class="line">   <span class="keyword">public</span>:</span><br><span class="line">      <span class="built_in">Line</span>(<span class="type">int</span> len);             <span class="comment">// 简单的构造函数</span></span><br><span class="line">      <span class="built_in">Line</span>(<span class="type">const</span> Line &amp;obj);      <span class="comment">// 拷贝构造函数</span></span><br><span class="line"> </span><br><span class="line">   <span class="keyword">private</span>:</span><br><span class="line">      <span class="type">int</span> *ptr;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">Line::<span class="built_in">Line</span>(<span class="type">const</span> Line &amp;obj)</span><br><span class="line">&#123;</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;调用拷贝构造函数并为指针 ptr 分配内存&quot;</span> &lt;&lt; endl;</span><br><span class="line">    ptr = <span class="keyword">new</span> <span class="type">int</span>;</span><br><span class="line">    *ptr = *obj.ptr; <span class="comment">// 拷贝值</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="friend-友元"><a href="#friend-友元" class="headerlink" title="friend 友元"></a>friend 友元</h2><p>类的友元函数是定义在类外部，但有权访问类的所有私有（private）成员和保护（protected）成员。尽管友元函数的原型有在类的定义中出现过，但是友元函数并不是成员函数。</p>
<p>友元也可以是一个类，该类被称为友元类类。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Box</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">   <span class="type">double</span> width;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">   <span class="function"><span class="keyword">friend</span> <span class="type">void</span> <span class="title">printWidth</span><span class="params">(Box box)</span></span>;</span><br><span class="line">   <span class="function"><span class="type">void</span> <span class="title">setWidth</span><span class="params">(<span class="type">double</span> wid)</span></span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 请注意：printWidth() 不是任何类的成员函数</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">printWidth</span><span class="params">(Box box)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   <span class="comment">/* 因为 printWidth() 是 Box 的友元，它可以直接访问该类的任何成员 */</span></span><br><span class="line">   cout &lt;&lt; <span class="string">&quot;Width of box : &quot;</span> &lt;&lt; box.width &lt;&lt;endl;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="inline-内联函数"><a href="#inline-内联函数" class="headerlink" title="inline 内联函数"></a>inline 内联函数</h2><p>如果一个函数是内联的，那么在编译时，编译器会把该函数的代码副本放置在每个调用该函数的地方。对内联函数进行任何修改，都需要重新编译函数的所有客户端，因为编译器需要重新更换一次所有的代码，否则将会继续使用旧的函数。</p>
<h2 id="继承类型"><a href="#继承类型" class="headerlink" title="继承类型"></a>继承类型</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Rectangle</span>: <span class="keyword">public</span> Shape </span><br><span class="line">&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<table>
<thead>
<tr>
<th>继承类型</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>public</td>
<td>基类的公有成员也是派生类的公有成员，基类的保护成员也是派生类的保护成员，基类的私有成员不能直接被派生类访问</td>
</tr>
<tr>
<td>protected</td>
<td>基类的公有和保护成员将成为派生类的保护成员。</td>
</tr>
<tr>
<td>private</td>
<td>基类的公有和保护成员将成为派生类的私有成员。</td>
</tr>
</tbody></table>
<h2 id="运算符重载"><a href="#运算符重载" class="headerlink" title="运算符重载"></a>运算符重载</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Box</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">   <span class="type">double</span> length;      <span class="comment">// 长度</span></span><br><span class="line">   <span class="type">double</span> breadth;     <span class="comment">// 宽度</span></span><br><span class="line">   </span><br><span class="line">   <span class="comment">// 重载 + 运算符，用于把两个 Box 对象相加</span></span><br><span class="line">   Box <span class="keyword">operator</span>+(<span class="type">const</span> Box&amp; b)</span><br><span class="line">   &#123;</span><br><span class="line">      Box box;</span><br><span class="line">      box.length = <span class="keyword">this</span>-&gt;length + b.length;</span><br><span class="line">      box.breadth = <span class="keyword">this</span>-&gt;breadth + b.breadth;</span><br><span class="line">      <span class="keyword">return</span> box;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="动态内存"><a href="#动态内存" class="headerlink" title="动态内存"></a>动态内存</h2><p>new 运算符为给定类型的变量在运行时分配堆内的内存，这会返回所分配的空间地址。如果不再需要动态分配的内存空间，可以使用 delete 运算符，删除之前由 new 运算符分配的内存。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">double</span>* pvalue = <span class="keyword">new</span> <span class="type">double</span></span><br><span class="line">···</span><br><span class="line"><span class="keyword">delete</span> pvalue; </span><br></pre></td></tr></table></figure>

<h2 id="命名空间"><a href="#命名空间" class="headerlink" title="命名空间"></a>命名空间</h2><p>命名空间的定义使用关键字 namespace，后跟命名空间的名称：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">namespace</span> namespace_name &#123;</span><br><span class="line">   <span class="comment">// 代码声明</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>为了调用带有命名空间的函数或变量，需要在前面加上命名空间的名称：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">name::code;  <span class="comment">// code 可以是变量或函数</span></span><br></pre></td></tr></table></figure>

<p>使用 using namespace 指令，这样在使用命名空间时就可以不用在前面加上命名空间的名称。这个指令会告诉编译器，后续的代码将使用指定的命名空间中的名称：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br></pre></td></tr></table></figure>

<h2 id="预处理器"><a href="#预处理器" class="headerlink" title="预处理器"></a>预处理器</h2><h3 id="include"><a href="#include" class="headerlink" title="#include"></a>#include</h3><p><strong>include</strong> 是一个来自 C 语言的宏命令，它在编译器进行编译之前，即在预编译的时候就会起作用。#include 的作用是把它后面所写的那个文件的内容一字不改地包含到当前的文件中来。值得一提的是，它本身是没有其它任何作用与副功能的，它的作用就是把每一个它出现的地方，替换成它后面所写的那个文件的内容。</p>
<ul>
<li>系统自带的头文件用尖括号括起来，这样编译器会在系统文件目录下查找。</li>
<li>用户自定义的文件用双引号括起来，编译器首先会在用户目录下查找，然后在到 C++ 安装目录（比如 VC 中可以指定和修改库文件查找路径，Unix 和 Linux 中可以通过环境变量来设定）中查找，最后在系统文件中查找。</li>
</ul>
<h3 id="define"><a href="#define" class="headerlink" title="#define"></a>#define</h3><p>#define 预处理指令用于创建符号常量。该符号常量通常称为宏，指令的一般形式是：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> macro-name replacement-text </span></span><br></pre></td></tr></table></figure>

<ul>
<li>示例<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> PI 3.14159</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> MIN(a,b) (a&lt;b ? a : b)</span></span><br></pre></td></tr></table></figure></li>
</ul>
<h3 id="条件编译"><a href="#条件编译" class="headerlink" title="条件编译"></a>条件编译</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> DEBUG</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">ifdef</span> DEBUG</span></span><br><span class="line">   cerr &lt;&lt;<span class="string">&quot;Trace: Inside main function&quot;</span> &lt;&lt; endl;</span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br></pre></td></tr></table></figure>

<h3 id="预定义宏"><a href="#预定义宏" class="headerlink" title="预定义宏"></a>预定义宏</h3><table>
<thead>
<tr>
<th>宏</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>__LINE__</td>
<td>程序编译时包含当前行号</td>
</tr>
<tr>
<td>__FILE__</td>
<td>程序编译时包含当前文件名</td>
</tr>
<tr>
<td>__DATE__</td>
<td>包含一个形式为 month&#x2F;day&#x2F;year 的字符串，它表示把源文件转换为目标代码的日期</td>
</tr>
<tr>
<td>__TIME__</td>
<td>包含一个形式为 hour:minute:second 的字符串，它表示程序被编译的时</td>
</tr>
</tbody></table>
<h2 id="信号"><a href="#信号" class="headerlink" title="信号"></a>信号</h2><table>
<thead>
<tr>
<th>信号</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>SIGABRT</td>
<td>程序的异常终止，如调用 abort</td>
</tr>
<tr>
<td>SIGFPE</td>
<td>错误的算术运算，比如除以零或导致溢出的操作</td>
</tr>
<tr>
<td>SIGILL</td>
<td>检测非法指令</td>
</tr>
<tr>
<td>SIGINT</td>
<td>程序终止(interrupt)信号</td>
</tr>
<tr>
<td>SIGSEGV</td>
<td>非法访问内存</td>
</tr>
<tr>
<td>SIGTERM</td>
<td>发送到程序的终止请求</td>
</tr>
</tbody></table>
<p>C++ 信号处理库提供了 signal 函数，用来捕获突发事件，raise 函数来生成信号：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;csignal&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">signalHandler</span><span class="params">( <span class="type">int</span> signum )</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;Interrupt signal (&quot;</span> &lt;&lt; signum &lt;&lt; <span class="string">&quot;) received.\n&quot;</span>;</span><br><span class="line">    <span class="built_in">exit</span>(signum);  </span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span> <span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">// 注册信号 SIGINT 和信号处理程序</span></span><br><span class="line">    <span class="built_in">signal</span>(SIGINT, signalHandler);  </span><br><span class="line">    <span class="built_in">raise</span>(SIGINT);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="线程"><a href="#线程" class="headerlink" title="线程"></a>线程</h2><p>c++ 11 之后有了标准的线程库</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;thread&gt;</span></span></span><br><span class="line"></span><br><span class="line">std::thread::id main_thread_id = std::this_thread::<span class="built_in">get_id</span>();</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">hello</span><span class="params">()</span>  </span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    std::cout &lt;&lt; <span class="string">&quot;Hello Concurrent World\n&quot;</span>;</span><br><span class="line">    <span class="keyword">if</span> (main_thread_id == std::this_thread::<span class="built_in">get_id</span>())</span><br><span class="line">        std::cout &lt;&lt; <span class="string">&quot;This is the main thread.\n&quot;</span>;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        std::cout &lt;&lt; <span class="string">&quot;This is not the main thread.\n&quot;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">pause_thread</span><span class="params">(<span class="type">int</span> n)</span> </span>&#123;</span><br><span class="line">    std::this_thread::<span class="built_in">sleep_for</span>(std::chrono::<span class="built_in">seconds</span>(n));</span><br><span class="line">    std::cout &lt;&lt; <span class="string">&quot;pause of &quot;</span> &lt;&lt; n &lt;&lt; <span class="string">&quot; seconds ended\n&quot;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="function">std::thread <span class="title">t</span><span class="params">(hello)</span></span>;</span><br><span class="line">    std::cout &lt;&lt; t.<span class="built_in">hardware_concurrency</span>() &lt;&lt; std::endl;<span class="comment">//可以并发执行多少个(不准确)</span></span><br><span class="line">    std::cout &lt;&lt; <span class="string">&quot;native_handle &quot;</span> &lt;&lt; t.<span class="built_in">native_handle</span>() &lt;&lt; std::endl;<span class="comment">//可以并发执行多少个(不准确)</span></span><br><span class="line">    t.<span class="built_in">join</span>();</span><br><span class="line">    <span class="function">std::thread <span class="title">a</span><span class="params">(hello)</span></span>;</span><br><span class="line">    a.<span class="built_in">detach</span>();</span><br><span class="line">    std::thread threads[<span class="number">5</span>];                         <span class="comment">// 默认构造线程</span></span><br><span class="line"></span><br><span class="line">    std::cout &lt;&lt; <span class="string">&quot;Spawning 5 threads...\n&quot;</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; ++i)</span><br><span class="line">        threads[i] = std::<span class="built_in">thread</span>(pause_thread, i + <span class="number">1</span>);   <span class="comment">// move-assign threads</span></span><br><span class="line">    std::cout &lt;&lt; <span class="string">&quot;Done spawning threads. Now waiting for them to join:\n&quot;</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">auto</span> &amp;thread : threads)</span><br><span class="line">        thread.<span class="built_in">join</span>();</span><br><span class="line">    std::cout &lt;&lt; <span class="string">&quot;All threads joined!\n&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="强制类型转换"><a href="#强制类型转换" class="headerlink" title="强制类型转换"></a>强制类型转换</h2><h3 id="const-cast"><a href="#const-cast" class="headerlink" title="const_cast"></a>const_cast</h3><p>const_cast 用于去除对象的 const 或 volatile 属性</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">Func</span><span class="params">(<span class="type">double</span>&amp; d)</span> </span>&#123; ... &#125;  </span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">ConstCast</span><span class="params">()</span>  </span></span><br><span class="line"><span class="function"></span>&#123;  </span><br><span class="line">   <span class="type">const</span> <span class="type">double</span> pi = <span class="number">3.14</span>;  </span><br><span class="line">   <span class="built_in">Func</span>(<span class="built_in">const_cast</span>&lt;<span class="type">double</span>&amp;&gt;(pi)); <span class="comment">// No error.  </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="static-cast"><a href="#static-cast" class="headerlink" title="static_cast"></a>static_cast</h3><p>static_cast 强制转换只会在编译时检查，但没有运行时类型检查来保证转换的安全性。同时，static_cast 也不能去掉 expression 的 const、volitale、或者 __unaligned 属性。</p>
<p>其主要应用场景有：</p>
<ul>
<li>用于类层次结构中基类（父类）和派生类（子类）之间指针或引用的转换。进行上行转换（把派生类的指针或引用转换成基类表示）是安全的；进行下行转换（把基类指针或引用转换成派生类表示）时，由于没有动态类型检查，所以是不安全的。</li>
<li>用于基本数据类型之间的转换，如把 int 转换成char，把 int 转换成enum。这种转换的安全性也要开发人员来保证。</li>
<li>把 void 转换成目标类型的空指针.</li>
<li>把任何类型的表达式转换成 void 类型。<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Sub sub;</span><br><span class="line">Base *base_ptr = <span class="built_in">static_cast</span>&lt;Base*&gt;(&amp;sub);  </span><br></pre></td></tr></table></figure></li>
</ul>
<h3 id="dynamic-cast"><a href="#dynamic-cast" class="headerlink" title="dynamic_cast"></a>dynamic_cast</h3><p>dynamic_cast 运算符的主要用途：将基类的指针或引用安全地转换成派生类的指针或引用。并用派生类的指针或引用调用非虚函数。</p>
<p>如果是基类指针或引用调用的是虚函数无需转换就能在运行时调用派生类的虚函数。</p>
<p>前提条件：当我们将 dynamic_cast 用于某种类型的指针或引用时，只有该类型至少含有虚函数时(最简单是基类析构函数为虚函数)，才能进行这种转换。否则，编译器会报错。</p>
<p>在指针类型中，基类指针所指对象为基类类型，在这种情况下 dynamic_cast 在运行时做检查，转换失败，返回结果为 0；</p>
<p>在引用类型中，并不存在空引用，所以引用的 dynamic_cast 检测失败时会抛出一个 bad_cast 异常。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Base * base = <span class="keyword">new</span> Base;</span><br><span class="line"><span class="keyword">if</span> (Derived *der = <span class="built_in">dynamic_cast</span>&lt;Derived*&gt;(base))</span><br><span class="line">&#123;</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;转换成功&quot;</span> &lt;&lt;endl;</span><br><span class="line">    der-&gt;<span class="built_in">Show</span>();</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">else</span> </span><br><span class="line">&#123;</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;转换失败&quot;</span> &lt;&lt;endl;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="reinterupt-cast"><a href="#reinterupt-cast" class="headerlink" title="reinterupt_cast"></a>reinterupt_cast</h3><p>reinterpret_cast 用来处理无关类型转换，通常为操作数的位模式提供较低层次的重新解释。</p>
<p>推荐使用在：</p>
<ul>
<li>从指针类型到一个足够大的整数类型</li>
<li>从整数类型或者枚举类型到指针类型</li>
<li>从一个指向函数的指针到另一个不同类型的指向函数的指针</li>
<li>从一个指向对象的指针到另一个不同类型的指向对象的指针</li>
<li>从一个指向类函数成员的指针到另一个指向不同类型的函数成员的指针</li>
<li>从一个指向类数据成员的指针到另一个指向不同类型的数据成员的指针</li>
</ul>
<p>错误的使用 reinterpret_cast 很容易导致程序的不安全，只有将转换后的类型值转换回到其原始类型，这样才是正确使用 reinterpret_cast 方式。</p>
<h2 id="智能指针"><a href="#智能指针" class="headerlink" title="智能指针"></a>智能指针</h2><h3 id="unique-ptr"><a href="#unique-ptr" class="headerlink" title="unique_ptr"></a>unique_ptr</h3><p>由 unique_ptr 管理的内存，只能被一个对象持有，所以，unique_ptr不支持复制和赋值。想要把一个 unique_ptr 的内存交给另外一个 unique_ptr 对象管理。只能使用 std::move 转移当前对象的所有权。转移之后，当前对象不再持有此内存，新的对象将获得专属所有权。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">auto</span> w = std::<span class="built_in">make_unique</span>&lt;Widget&gt;();</span><br><span class="line"><span class="keyword">auto</span> w2 = std::<span class="built_in">move</span>(w); <span class="comment">// w2 获得内存所有权，w 此时等于 nullptr</span></span><br></pre></td></tr></table></figure>

<p>unique_ptr在默认情况下和裸指针的大小是一样的，所以内存上没有任何的额外消耗，性能是最优的。</p>
<h3 id="shared-ptr"><a href="#shared-ptr" class="headerlink" title="shared_ptr"></a>shared_ptr</h3><p>多个智能指针可以共享同一个对象。shared_ptr 内部是利用引用计数来实现内存的自动管理，每当复制一个 shared_ptr，引用计数会 +1。当一个 shared_ptr 离开作用域时，引用计数会 -1。当引用计数为0的时候，则 delete 内存。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">auto</span> w = std::<span class="built_in">make_shared</span>&lt;Widget&gt;();</span><br></pre></td></tr></table></figure>

<p>shared_ptr的内存占用是裸指针的两倍。因为除了要管理一个裸指针外，还要维护一个引用计数。</p>
<h3 id="weak-ptr"><a href="#weak-ptr" class="headerlink" title="weak_ptr"></a>weak_ptr</h3><p>允许你共享但不拥有某对象，一旦最末一个拥有该对象的智能指针失去了所有权，任何 weak_ptr 都会自动成空。</p>
<h2 id="内存空间"><a href="#内存空间" class="headerlink" title="内存空间"></a>内存空间</h2><table>
<thead>
<tr>
<th>区</th>
<th>秒速</th>
</tr>
</thead>
<tbody><tr>
<td>堆</td>
<td>操作系统维护的一块动态分配内存，malloc 在堆上分配的内存块，使用 free 释放内存</td>
</tr>
<tr>
<td>栈</td>
<td>由编译器自动分配释放，存放函数的参数值，局部变量的值等</td>
</tr>
<tr>
<td>自由存储区</td>
<td>C++ 中通过 new 与 delete 动态分配和释放对象的抽象概念</td>
</tr>
<tr>
<td>全局区（静态区）</td>
<td>全局变量和静态变量分配在此一块内存中</td>
</tr>
<tr>
<td>常量存储区</td>
<td>存储常量字符串, 程序结束后由系统释放</td>
</tr>
</tbody></table>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/hello-world/about" rel="external nofollow noreferrer">Easy Zhang</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://cainiaodashixiong.gitee.io/hello-world/hello-world/2022/11/28/C++%E7%9F%A5%E8%AF%86%E7%82%B9%E6%B1%87%E6%80%BB/">https://cainiaodashixiong.gitee.io/hello-world/hello-world/2022/11/28/C++%E7%9F%A5%E8%AF%86%E7%82%B9%E6%B1%87%E6%80%BB/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/hello-world/about" target="_blank">Easy Zhang</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/hello-world/tags/%E5%AD%A6%E4%B9%A0/">
                                    <span class="chip bg-color">学习</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/hello-world/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/hello-world/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/hello-world/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/hello-world/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/hello-world/2022/11/28/Gradle%E7%9F%A5%E8%AF%86%E7%82%B9%E6%B1%87%E6%80%BB/">
                    <div class="card-image">
                        
                        
                        <img src="/hello-world/medias/featureimages/1.jpg" class="responsive-img" alt="Gradle 知识点">
                        
                        <span class="card-title">Gradle 知识点</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2022-11-28
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            Easy Zhang
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/hello-world/tags/%E5%AD%A6%E4%B9%A0/">
                        <span class="chip bg-color">学习</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/hello-world/2022/11/28/Android%E7%9F%A5%E8%AF%86%E7%82%B9%E6%B1%87%E6%80%BB/">
                    <div class="card-image">
                        
                        
                        <img src="/hello-world/medias/featureimages/3.jpg" class="responsive-img" alt="Android 知识点汇总">
                        
                        <span class="card-title">Android 知识点汇总</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2022-11-28
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            Easy Zhang
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/hello-world/tags/%E5%AD%A6%E4%B9%A0/">
                        <span class="chip bg-color">学习</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/hello-world/libs/codeBlock/codeBlockFuction.js"></script>



<!-- 代码语言 -->

<script type="text/javascript" src="/hello-world/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/hello-world/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/hello-world/libs/codeBlock/codeShrink.js"></script>



    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/hello-world/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/hello-world/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/hello-world/libs/aplayer/APlayer.min.js"></script>
<script src="/hello-world/libs/aplayer/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2023</span>
            
            <a href="/hello-world/about" target="_blank">Easy Zhang</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://gitee.com/CaiNiaoDaShiXiong" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:838489284@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=838489284" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 838489284" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/hello-world/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/hello-world/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 白天和黑夜主题 -->
<div class="stars-con">
    <div id="stars"></div>
    <div id="stars2"></div>
    <div id="stars3"></div>  
</div>

<script>
    function switchNightMode() {
        $('<div class="Cuteen_DarkSky"><div class="Cuteen_DarkPlanet"></div></div>').appendTo($('body')),
        setTimeout(function () {
            $('body').hasClass('DarkMode') 
            ? ($('body').removeClass('DarkMode'), localStorage.setItem('isDark', '0'), $('#sum-moon-icon').removeClass("fa-sun").addClass('fa-moon')) 
            : ($('body').addClass('DarkMode'), localStorage.setItem('isDark', '1'), $('#sum-moon-icon').addClass("fa-sun").removeClass('fa-moon')),
            
            setTimeout(function () {
            $('.Cuteen_DarkSky').fadeOut(1e3, function () {
                $(this).remove()
            })
            }, 2e3)
        })
    }
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/hello-world/libs/materialize/materialize.min.js"></script>
    <script src="/hello-world/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/hello-world/libs/aos/aos.js"></script>
    <script src="/hello-world/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/hello-world/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/hello-world/js/matery.js"></script>

    

    

    <!-- 雪花特效 -->
    

    <!-- 鼠标星星特效 -->
     
        <script type="text/javascript">
            // 只在桌面版网页启用特效
            var windowWidth = $(window).width();
            if (windowWidth > 768) {
                document.write('<script type="text/javascript" src="/hello-world/libs/others/star.js"><\/script>');
            }
        </script>
    

     
        <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
        <script src="/hello-world/libs/others/TencentCaptcha.js"></script>
        <button id="TencentCaptcha" data-appid="xxxxxxxxxx" data-cbfn="callback" type="button" hidden></button>
    

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/hello-world/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/hello-world/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/hello-world/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
